const zbTabNav = function() {
    this.activeClass = 'zb-tabnav-active';
    this.content = ''; //渲染后的内容，类型为字符串
    this.contentNode = null;
    this.navId = ''; //导航元素的id
    this.contentId = ''; //内容元素的id

    //切换tab事件回调
    this.onChangeTab = function () {
        console.log(this);
    };

    //第一次初始化页面后的回调
    this.onShow = function () {
        console.log(this);
    };

    this.tpl =
        '<div class="zb-tabnav">\
            <div class="zb-tabnav-nav" id="{id}" data-active-tab="">\
                <div class="zb-tabnav-tab" id="{id}">{name}</div>\
            </div>\
            <div class="zb-tabnav-content" id="{id}"></div>\
        </div>';

    this.initCss = function() {
        let flag = document.getElementsByClassName('zb-tabnav');
        if (!flag || flag.length === 0) {
            let style = document.createElement('style');
            style.innerText =
                '.zb-tabnav-nav{display:flex;flex-direction:row;justify-content:flex-start;overflow-x:scroll; white-space: nowrap;}'+
                '.zb-tabnav-nav::-webkit-scrollbar {display:none}'+
                '.zb-tabnav-tab{margin:8px;padding-bottom:5px;}'+
                '.zb-tabnav-active{border-bottom: 2px solid #7E57C2;}'+
                '.zb-tabnav-content{padding:5px;}'
            ;

            let head = document.getElementsByTagName('head')[0];
            head.appendChild(style);
        }
    }

    //初始化
    //config: {nav: [导航数组, 元素包含：name, id, url]， content_id: 存放内容的元素的id属性}
    this.init = function(config){
        this.initCss();

        this.navId = config['nav_id'] ? config['nav_id'] : 'navTabList';
        this.contentId = config['content_id'] ? config['content_id'] : 'navContent';

        let data = {
            'zb-tabnav-nav': {
                'id': this.navId,
                'zb-tabnav-tab' : config['tabs'],
            },
            'zb-tabnav-content' : {
                'id' : this.contentId
            }
        }

        if (config['active_class']) {
            this.activeClass = config['active_class'];
        }

        let node = this.htmlToNode(this.tpl);
        this.content = this.repeatNode(node, [data]);
        this.contentNode = this.htmlToNode(this.content);

        let items = this.contentNode.getElementsByClassName('zb-tabnav-tab');
        for (let i=0; i<items.length; i++) {
            let tab_id = items[i].getAttribute('id')
            items[i].addEventListener('click', this.changeTabById.bind(this, tab_id));
        }
    }

    //获取所有的tab
    this.getNavTabList = function () {
        //找到所有的tab
        let nav = document.getElementById(this.navId);
        return nav.getElementsByClassName('zb-tabnav-tab');
    }

    //将渲染后的内容覆盖到某个id元素中
    this.show = function(id) {
        document.getElementById(id).innerHTML = this.content;
        if (typeof this.onShow === 'function') {
            this.onShow();
        }
    }

    //根据tab索引值切换tab
    this.changeTab = function(index){
        //找到所有的tab
        let navList = this.getNavTabList();
        if (index > navList.length) {
            index = navList.length;
        }

        //找到指定tab
        let selected = navList[index];
        let id = selected.getAttribute('id');

        //高亮此tab
        this.activeTab(id);

        //记录当前tab
        let nav = document.getElementById(this.navId);
        nav.setAttribute('data-active-tab', id);

        //回调
        if (typeof this.onChangeTab === 'function') {
            this.onChangeTab(id);
        }
    }

    //根据ID切换导航
    this.changeTabById = function (tab_id) {
        //高亮此tab
        this.activeTab(tab_id);

        //记录当前tab
        let nav = document.getElementById(this.navId);
        nav.setAttribute('data-active-tab', tab_id);

        //回调
        if (typeof this.onChangeTab === 'function') {
            this.onChangeTab(tab_id);
        }
    }

    //获取当前
    this.getActiveTabId = function () {
        return document.getElementById(this.navId).getAttribute('data-active-tab');
    }

    //更改content
    this.updateContent = function (str) {
        document.getElementById(this.contentId).innerHTML = str;
    }

    //更改node
    this.updateNode = function (node) {
        let contentBox = document.getElementById(this.contentId);
        contentBox.innerHTML = '<div id="tmp_nav_content"></div>';
        let tmp = document.getElementById('tmp_nav_content');
        contentBox.replaceChild(node, tmp);
    }

    //用本插件生成的node, 替换指定id的节点
    this.replaceDom = function (id) {
        let old = document.getElementById(id)
        let parent = old.parentNode;
        parent.replaceChild(this.contentNode, old);
    }

    //用本插件生成的node, 替换指定id的节点的内容
    this.updateDom = function (id) {
        let contentBox = document.getElementById(id);
        contentBox.innerHTML = '<div id="tmp_nav"></div>';
        let tmp = document.getElementById('tmp_nav');
        contentBox.replaceChild(this.contentNode, tmp);
    }

    //追加content
    this.appendContent = function (str) {
        document.getElementById(this.contentId).innerHTML += str;
    }

    //追加node
    this.appendNode = function (node) {
        document.getElementById(this.contentId).appendChild(node);
    }

    this.activeTab = function(id) {
        if (document.getElementById(id) !== null) {
            let brothers = document.getElementById(id).parentNode.children;
            for (let i=0; i<brothers.length; i++) {
                brothers[i].classList.remove(this.activeClass);
            }

            document.getElementById(id).classList.add(this.activeClass);
        }
    }

    this.htmlToNode = function(html) {
        let div = document.createElement('div');
        div.innerHTML = html;
        return div.firstElementChild;
    }

    /**
     * 根据json渲染DOM节点
     * @param node HTML DOM节点, 注意不是string
     * @param arr json数组 注意是数组类型
     * @return string 返回HTML字符串, 注意不是DOM节点
     */
    this.repeatNode = function (node, arr) {
        let out = [];
        for (let i=0; i<arr.length; i++) {
            let tmp = node.outerHTML;
            tmp = tmp.replace(/\s/g, ' '); //去掉回车换行, 减少空白符

            let map = arr[i];

            //先渲染内层的数组
            for (let j in map) {
                if (map[j] instanceof Array) { //数组, 递归替换
                    let subNode = node.querySelector('.'+j);
                    if (subNode) {
                        let subHtml = this.repeatNode(subNode, map[j]); //递归
                        let subTpl = subNode.outerHTML.replace(/\s/g, ' ');
                        tmp = tmp.replace(subTpl, subHtml);
                    }
                }
            }

            //再渲染内层的对象
            for (let j in map) {
                if (map[j] instanceof Object && !(map[j] instanceof Array)) { //对象, 递归替换
                    let subNode = node.querySelector('.'+j);
                    if (subNode) {
                        let subHtml = this.repeatNode(subNode, [map[j]]); //递归
                        let subTpl = subNode.outerHTML.replace(/\s/g, ' ')
                        tmp = tmp.replace(subTpl, subHtml);
                    }
                }
            }

            //最后渲染外层的键值对/字符串
            for (let j in map) {
                if (typeof map[j] === 'string' || typeof map[j] === 'number') { //字符串, 直接替换
                    let re = new RegExp('{' + j + '}', 'g');
                    tmp = tmp.replace(re, map[j]);
                }
            }

            out.push(tmp);
        }

        return out.join('');
    }

    this.repeatString = function (tplDom, arr, func=null) {
        if (tplDom.length === 0) {
            this.error('字符串长度为空');
            return;
        }

        if (arr.length === 0) {
            this.error('数据为空');
            return tplDom;
        }

        let tpl = tplDom;
        let out = '';
        for (let i=0; i<arr.length; i++) {
            if (typeof func === 'function') {
                arr[i] = func(arr[i]);
            }
            let map = arr[i];
            let tmp = tpl;
            for (let j in map) {
                let re = new RegExp('{' + j + '}', 'g');
                tmp = tmp.replace(re, map[j]);
            }

            let re = new RegExp('{_idx}', 'g');
            tmp = tmp.replace(re, parseInt(i)+1);

            out += tmp;
        }

        return out;
    };
}
/**
 *使用举例
 let navCate = new zbTabNav();
 navCate.init({
    active_class:class_name, //active_class:高亮当前选中tab的样式名
    nav_id: 'navCate', //导航最外部的ID
    content_id: 'navContentId', //导航内容区域的ID
    tabs: [{name:'', id:''}], //导航标题信息
    });
 navCate.onChangeTab = function (id) {
        navCate.updateContent('html here ...');
        //navCate.updateNode(node here...);
    }
 navCate.replaceDom('container');//把HTML替换到指定id的dom
 navCate.changeTab(0); //触发导航切换, 参数为整数, 表示tab的索引
 // navCate.changeTabById('id'); //触发导航切换, 参数为字符串, 表示tab的id属性
 */